package com.czkj.hwz.decorate.Activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czkj.hwz.decorate.MyApp;
import com.czkj.hwz.decorate.R;
import com.czkj.hwz.decorate.base.HttpUrl;
import com.czkj.hwz.decorate.bean.Enterprise;
import com.czkj.hwz.decorate.bean.Goods;
import com.czkj.hwz.decorate.bean.MyTab;
import com.czkj.hwz.decorate.bean.Sort;
import com.joanzapata.android.BaseAdapterHelper;
import com.joanzapata.android.QuickAdapter;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ClassifyActivity3 extends AppCompatActivity {
    private static final String TAG = "ClassifyActivity3";
    private LinearLayout ll_h;
    private LinearLayout ll;
    private TextView tv_qb;
    private GridView gv_qb;
    private FinalBitmap fb;
    private List<Goods> mGoodsList;
    private List<Enterprise> mEnterpriseList;
    private List<Sort> mGoodsSort;
    private QuickAdapter<Goods> mAdapter;
    private MyTab mMyTab_v,mMyTab_h;
    private int enterpriceId;//运营商ID
    private String mTitle;//运营商
    private int sortId;//产品Id
    private RelativeLayout iv_back;
    private RelativeLayout iv_search;
    private Handler mHandler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ll_h.removeAllViews();
                    mMyTab_h.setData(mEnterpriseList);
                    enterpriceId=mEnterpriseList.get(0).getId();
                    mTitle=mEnterpriseList.get(0).getName();
                    getGoodList(sortId,enterpriceId);
                    ll_h.addView(mMyTab_h.getView());
                    if (mMyTab_h!=null) {
                        mMyTab_h.changeColor(0);
                    }
                    break;
                case 1:
                    ll.removeAllViews();
                    mMyTab_v.setData(mGoodsSort);

                    ll.addView(mMyTab_v.getView());
                    mMyTab_v.setText_Qb(tv_qb);
                    break;
                case 2:
                    mAdapter=new QuickAdapter<Goods>(ClassifyActivity3.this,R.layout.grideview_goods_item,mGoodsList) {
                        @Override
                        protected void convert(BaseAdapterHelper helper, Goods item) {
                            helper.setText(R.id.tv_title,item.getName());
                            ImageView img=helper.getView(R.id.img);
                            fb.display(img, HttpUrl.BASE_URL+item.getSmallImg());
                        }
                    };

                    gv_qb.setAdapter(mAdapter);



            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.yellow));
        }
        setContentView(R.layout.activity_classify3);
        getSupportActionBar().hide();
        sortId = -1000;//设置为-1000,方便后面选择全部商品
        initView();
        initData();


        getList();
        getGoodSortList();

        if (fb == null) {
            fb = FinalBitmap.create(this);
            fb.configBitmapMaxHeight(150);
            fb.configBitmapMaxWidth(150);
        }

    }

    private void initView() {
        iv_back = (RelativeLayout) findViewById(R.id.iv_back);
        iv_search= (RelativeLayout) findViewById(R.id.iv_search);
        ll_h = (LinearLayout) findViewById(R.id.ll_h);
        ll = (LinearLayout) findViewById(R.id.ll);
        gv_qb = (GridView) findViewById(R.id.gv_qb);
        tv_qb = (TextView) findViewById(R.id.tv_qb);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClassifyActivity3.this.finish();
            }
        });
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ClassifyActivity3.this,ProductActivity.class);
                MyApp app = (MyApp) getApplication();
                app.setmEnterpriseList(mEnterpriseList);

                intent.putExtra("mEnterpriseList", (Serializable) mEnterpriseList);
                startActivity(intent);
            }
        });
        gv_qb.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemClick: " + position);
                Log.d(TAG, "onItemClick: " + id);
                Intent intent = new Intent(ClassifyActivity3.this, DetailActivity.class);
                intent.putExtra("mTitle",mTitle);
                intent.putExtra("mGoodsList", (Serializable) mGoodsList);
                intent.putExtra("position", position);
                startActivity(intent);


            }
        });
        mMyTab_h = new MyTab(this, LinearLayout.HORIZONTAL) {
            @Override
            public void onItemClickListener(int poistion) {
                enterpriceId = mEnterpriseList.get(poistion).getId();
                mTitle=mEnterpriseList.get(poistion).getName();
                getGoodList(sortId, enterpriceId);
            }
        };
        mMyTab_v = new MyTab(this, LinearLayout.VERTICAL) {
            @Override
            public void onItemClickListener(int poistion) {
                sortId = mGoodsSort.get(poistion).getId();
                getGoodList(sortId, enterpriceId);
            }
        };
        tv_qb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_qb.setTextColor(ClassifyActivity3.this.getResources().getColor(R.color.yellow));
                mMyTab_v.changeColor(-1);
                sortId = -1000;
                getGoodList(sortId, enterpriceId);
            }
        });
    }
    private void initData() {
        mGoodsList = new ArrayList<Goods>();
        mEnterpriseList = new ArrayList<Enterprise>();
        mGoodsSort = new ArrayList<Sort>();

    }
    //获取运营中心数据及
    private void getList() {
        FinalHttp fh = new FinalHttp();
        AjaxParams params = new AjaxParams();
        params.put("longitude", "119.038657");
        params.put("latitude", "33.609279");
        fh.get(HttpUrl.INDEX_GET, params, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (o != null) {
                    Log.d(TAG, "onSuccess:.......... " + o.toString());
                }
                parseListJson(o.toString());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    private void parseListJson(String json) {
        try {
            JSONObject jsonResult = new JSONObject(json);
            JSONObject areaInfo = jsonResult.getJSONObject("AreaInfo");
            String state = areaInfo.getString("state");
            JSONObject result = areaInfo.getJSONObject("result");
            Log.d(TAG, "parseListJson: " + state);
            Log.d(TAG, "parseListJson: " + result.toString());
            JSONArray banner = jsonResult.getJSONArray("Banner");
            Log.d(TAG, "parseListJson: " + banner);
            String[] imgUrls = new String[banner.length()];
            for (int i = 0; i < banner.length(); i++) {
                String url = HttpUrl.BASE_URL + banner.get(i);
                Log.d(TAG, "parseListJson: " + url);
                imgUrls[i] = url;
            }
            JSONArray enterprise = jsonResult.getJSONArray("Enterprise");
            if (enterprise != null && enterprise.length() > 0) {
                mEnterpriseList.clear();
                for (int i = 0; i < enterprise.length(); i++) {
                    JSONObject obj = enterprise.getJSONObject(i);
                    Enterprise mEnterprise = new Enterprise();
                    mEnterprise.setName(obj.optString("Name"));
                    mEnterprise.setId(obj.optInt("Id"));
                    mEnterprise.setEnable(obj.optBoolean("IsEnable"));
                    mEnterprise.setDelete(obj.optBoolean("IsDelete"));
                    mEnterprise.setRemark(obj.optString("Remark"));
                    mEnterprise.setSeq(obj.optInt("Seq"));
                    mEnterprise.setHeadImg(HttpUrl.BASE_URL + obj.optString("HeadImg"));
                    mEnterprise.setBackgroundImg(HttpUrl.BASE_URL + obj.optString("BackgroundImg"));
                    mEnterprise.setLongitude(obj.optDouble("Longitude"));
                    mEnterprise.setLatitude(obj.optDouble("Latitude"));
                    mEnterprise.setAreaCode(obj.optString("AreaCode"));
                    mEnterprise.setAreaName(obj.optString("AreaName"));
                    mEnterpriseList.add(mEnterprise);

                }
                mHandler.sendEmptyMessage(0);
            }
//
//            JSONArray GoodsArray=jsonResult.getJSONArray("Goods");
//            if (GoodsArray!=null && GoodsArray.length()>0) {
//                mGoodsList.clear();
//                for (int i=0;i<GoodsArray.length();i++) {
//                    JSONObject obj=GoodsArray.getJSONObject(i);
//                    Goods goods=new Goods();
//                    goods.setId(obj.optInt("Id"));
//                    goods.setName(obj.optString("Name"));
//                    goods.setImg(HttpUrl.BASE_URL+obj.optString("Img"));
//                    goods.setSelfSupport(obj.optBoolean("SelfSupport"));
//                    goods.setWorkerReward(obj.optInt("WorkerReward"));
//                    goods.setReferenceReward(obj.optInt("ReferenceReward"));
//                    goods.setPrice(obj.optLong("price"));
//                    mGoodsList.add(goods);
//                }
////                mHandler.sendEmptyMessage(2);
//            }

            JSONArray sortListArray = jsonResult.getJSONArray("SortList");
            if (sortListArray != null && sortListArray.length() > 0) {
                mGoodsSort.clear();
                for (int i = 0; i < sortListArray.length(); i++) {
                    JSONObject obj = sortListArray.getJSONObject(i);
                    Sort sort = new Sort();
                    sort.setId(obj.optInt("Id"));
                    sort.setName(obj.optString("Name"));
                    mGoodsSort.add(sort);

                }
                mHandler.sendEmptyMessage(1);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void getGoodSortList() {
        FinalHttp fh=new FinalHttp();
        AjaxParams params=new AjaxParams();
        params.put("longitude", "119.038657");
        params.put("latitude", "33.609279");
        fh.get(HttpUrl.GOODS_SORT, params, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (o!=null) {
                    Log.d(TAG, "onSuccess:.......... "+o.toString());
                }
                parseGoodSortList(o.toString());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    private void parseGoodSortList(String json) {
        try {
            JSONObject jsonResult=new JSONObject(json);
            JSONObject areaInfo=jsonResult.getJSONObject("AreaInfo");
            String state=areaInfo.getString("state");
            JSONObject result=areaInfo.getJSONObject("result");
            Log.d(TAG, "parseListJson: "+state);
            Log.d(TAG, "parseListJson: "+result.toString());

            JSONArray sortListArray=jsonResult.getJSONArray("SortList");
            if (sortListArray!=null && sortListArray.length()>0) {
                mGoodsSort.clear();
                for (int i=0;i<sortListArray.length();i++) {
                    JSONObject obj=sortListArray.getJSONObject(i);
                    Sort sort=new Sort();
                    sort.setId(obj.optInt("Id"));
                    sort.setName(obj.optString("Name"));
                    mGoodsSort.add(sort);

                }
                mHandler.sendEmptyMessage(1);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void getGoodList(int sortId,int enterpriceId) {
        FinalHttp fh=new FinalHttp();
        AjaxParams params=new AjaxParams();
        params.put("enterpriseid",String.valueOf(enterpriceId));
        params.put("classid",String.valueOf(sortId));
        fh.get(HttpUrl.GOODS_GET, params, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (o!=null) {
                    Log.d(TAG, "onSuccess:.......... "+o.toString());
                }
                parseGoodList(o.toString());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    private void parseGoodList(String json) {
        try {
            JSONObject jsonResult=new JSONObject(json);
            String total=jsonResult.getString("total");
            JSONArray rowArray=jsonResult.getJSONArray("rows");
            mGoodsList.clear();
            if (rowArray!=null && rowArray.length()>0) {
                mGoodsList.clear();
                for (int i=0;i<rowArray.length();i++) {
                    Goods goods=new Goods();
                    JSONObject obj=rowArray.getJSONObject(i);
                    goods.setId(obj.optInt("Id"));
                    goods.setName(obj.optString("Name"));
                    goods.setRemark(obj.optString("Remark"));
                    goods.setSeq(obj.optInt("Seq"));
                    goods.setHotSale(obj.optBoolean("HotSale"));
                    goods.setNewGoods(obj.optBoolean("NewGoods"));
                    goods.setContent(obj.optString("Content"));
                    goods.setGuid(obj.optString("Guid"));
                    goods.setUnit(obj.optString("Unit"));
                    goods.setPrice(obj.optLong("Price"));
                    goods.setInTime(obj.optString("InTime"));
                    goods.setOriginalPrice((float) obj.optDouble("OriginalPrice"));
                    goods.setCostPrice((float) obj.optDouble("CostPrice"));
                    goods.setGoodsClassName(obj.optString("GoodsClassName"));
                    goods.setBigImg(obj.optString("BigImg"));
                    goods.setSmallImg(obj.optString("SmallImg"));
                    goods.setGoodsClassId(obj.optInt("GoodsClassId"));
                    goods.setEnterpriseId(obj.optInt("EnterpriseId"));
                    goods.setWorkerReward(obj.optInt("WorkerReward"));
                    goods.setReferenceReward(obj.optInt("ReferenceReward"));
                    goods.setSelfSupport(obj.optBoolean("SelfSupport"));
                    mGoodsList.add(goods);
                }
                mHandler.sendEmptyMessage(2);
            }
            mHandler.sendEmptyMessage(2);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
